package com.runchinaup.smartbelt.ble;

import android.util.Log;

import com.runchinaup.smartbelt.domian.AlarmCanData;
import com.runchinaup.smartbelt.domian.AlarmData;
import com.runchinaup.smartbelt.domian.BleData;
import com.runchinaup.smartbelt.domian.BleDevice;
import com.runchinaup.smartbelt.domian.ElectricityAndTimeData;
import com.runchinaup.smartbelt.domian.PhoneCallAndMessage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by liber on 2018/1/25.
 */

public class BlueGattCallbackHelper {


    private BlueGattCallbackHelper() {
    }

    private volatile static BlueGattCallbackHelper blueGattCallbackHelper = null;

    public static BlueGattCallbackHelper getBlueGattCallbackHelper() {
        if (blueGattCallbackHelper == null) {
            synchronized (BlueGattCallbackHelper.class) {
                if (blueGattCallbackHelper == null) {
                    blueGattCallbackHelper = new BlueGattCallbackHelper();
                }
            }
        }
        return blueGattCallbackHelper;
    }

    PhoneCallAndMessage phoneCallAndMessage = new PhoneCallAndMessage();

    //用于保存现代模式下的设备
    private ArrayList<String> modernDevice = new ArrayList<>();

    //记录意外断开的设备，手动断开的不在里面
    private ArrayList<BleDevice> disDevice = new ArrayList<>();

    //记录已经连接的设备，第一个是对应圆环的索引
    HashMap<String, BleDevice> deviceList = new HashMap();
    private OnCallBackListener callBackListener;

    //添加圆环的索引，取不到设备的信息
    public void addModernDevice(String position) {
        if (!modernDevice.contains(position)) {
            modernDevice.add(position);
        }
    }

    public ArrayList<String> getModernDevice() {
        return modernDevice;
    }

    //移除现代模式下的设备
    public void removeModernDevice(String position) {
        if (modernDevice.contains(position)) {
            modernDevice.remove(position);
        }
    }


    public ArrayList<BleDevice> getDisDevice() {
        return disDevice;
    }

    public void setDisDevice(BleDevice bleDevice) {
        disDevice.add(bleDevice);
    }

    public void removeDisDevice(BleDevice bleDevice) {
        for (int i = 0; i < disDevice.size(); i++) {
            if (disDevice.get(i).getAddress().equals(bleDevice.getAddress())) {
                disDevice.remove(disDevice.get(i));
            }
        }
    }

    public void putDeviceList(String bluetoothPosition, BleDevice device) {
        deviceList.put(bluetoothPosition, device);
    }

    public void removeDeviceList(String bluetoothPosition) {
        if (deviceList.containsKey(bluetoothPosition)) {
            deviceList.remove(bluetoothPosition);
        }
    }


    //连接蓝牙，连接成功后的回调到这里
    public void linkBle(final String bluetoothPosition, final BleDevice device, OnCallBackListener listener) {
        this.callBackListener = listener;
        device.linkBle(new OnBleClickListenter() {      //连接完成后的回调,给主界面
            @Override
            public void onLink(BleDevice bleDevice) {
                //将成功连接的设备保存起来
                deviceList.put(bluetoothPosition, bleDevice);
                //回调出去
                callBackListener.linkCall(bluetoothPosition, bleDevice);
            }

            @Override
            public void onState(int state) {
                callBackListener.onState(state, bluetoothPosition, device);
            }

            @Override
            public void onExceptionDis(BleDevice device) {
                if (disDevice.indexOf(device) == -1) {
                    Log.e("debug_onExceptionDis", device.toString());
                    if (deviceList.containsValue(device)) {
                        disDevice.add(device);
                    }
                }
                callBackListener.onExceptionDis(bluetoothPosition, device);
            }

            @Override
            public void getElectricity(byte[] data) {
                callBackListener.getElectricity(data);
            }

            @Override
            public void getAlarmCan(byte[] data) {
                callBackListener.getAlarmCan(data);
            }

            @Override
            public void getAlarmTime(byte[] data) {
                callBackListener.getAlarmTime(data);
            }
        });
    }

    //返回连接的数组
    public ArrayList<String> getHadConnectBlue() {
        ArrayList<String> list = new ArrayList<>();
        Iterator iter = deviceList.entrySet().iterator();
        while (iter.hasNext()) {
            HashMap.Entry entry = (HashMap.Entry) iter.next();
            String key = (String) entry.getKey();
            BleDevice value = (BleDevice) entry.getValue();

            if (!list.contains(value)) {
                if (value.getAddress() != null) {
                    list.add(value.getAddress());
                }
            }
        }

        return list;
    }

    //判断是否连接成功  传来对应圆环按钮的蓝牙是否连接成功
    public boolean isConnect(String position) {
        if (!deviceList.containsKey(position))
            return false;
        if (!deviceList.containsValue(deviceList.get(position)))
            return false;
        return true;
    }

    //是否有设备已经连接     有设备已经连接的返回true
    public boolean hadConnect() {
        if (deviceList.size() > 0) {
            return true;
        } else return false;
    }

    //手动断开连接
    public void unLink(String position) {
        if (deviceList.containsValue(deviceList.get(position))) {
            BleDevice device = deviceList.get(position);
            device.disBlueConnect();
            deviceList.remove(position);
        } else {
            Log.e("unLink", "is null");
        }
    }

    //控制蓝牙，设置参数   向蓝牙设备发送数据(传统模式下)
    public void ControllBle(BleData bleData) {
        Log.e("ControllBle: ", modernDevice.size() + "");
        sendBleData(bleData.packData());
    }

    //控制蓝牙设备  想蓝牙设备发送数据
    public void ControllBleByModern(BleData bleData) {
        sendBleDataByModern(bleData.packData());
    }

    //来电提醒
    public void phoneCallRemind() {
        sendToAllDevice(phoneCallAndMessage.remindByPhone());
    }

    //短信提醒
    public void phoneMessageRemind() {
        sendToAllDevice(phoneCallAndMessage.remindByMessage());
    }

    //手机防丢失
    public void phoneLoose() {
        sendToAllDevice(phoneCallAndMessage.remindPhoneLoose());
    }

    //设置闹钟
    public void setAlarmData(AlarmData alarmData) {
        Log.e("setAlarmData: ", "is send");
        sendToAllDevice(alarmData.remindByAlarm());
    }

    //闹钟使能
    public void setCanAlarm(AlarmCanData alarmCanData) {
        Log.e("setCanAlarm: ", "is send");
        sendToAllDevice(alarmCanData.canAlarm());
    }

    //发送数据获取闹钟使能
    public void getCanAlarm() {
        AlarmCanData alarmCanData = new AlarmCanData();
        Log.e("getCanAlarm: aaa", alarmCanData.isOneAlarm() + "");
        sendToAllDevice(alarmCanData.getAlarmCan());
    }

    //发送数据获取闹钟时间
    public void getAlarmTime(int i) {
        AlarmData alarmData = new AlarmData();
        sendToAllDevice(alarmData.getAlarmTime(i));
    }

    //发送数据给蓝牙       传统模式下(默认)
    private void sendBleData(byte[] value) {
        Log.e("deviceList", deviceList.size() + "");
        for (int i = 0; i < 6; i++) {
            if (deviceList.get(i + "") != null) {
                if (modernDevice.contains(i + "")) continue;
                deviceList.get(i + "").sendData(value);
                Log.e("sendBleData", deviceList.get(i + "").getAddress());
            }
        }
    }

    //发送数据给蓝牙       现代模式下
    private void sendBleDataByModern(byte[] value) {
        Log.e("deviceList", deviceList.size() + "");
        for (int i = 0; i < 6; i++) {
            if (deviceList.get(i + "") != null) {
                if (modernDevice.contains(i + "")) {
                    deviceList.get(i + "").sendData(value);
                    Log.e("sendBleDataByModern: ", "send");
                } else {
                    Log.e("sendBleDataByModern: ", "no send");
                }
            }
        }
    }

    private void sendToAllDevice(byte[] value) {
        sendBleData(value);
        sendBleDataByModern(value);
    }

    //发送请求对应设备的电量
    public void sendForElectricity(String bluetoothPosition) {
        ElectricityAndTimeData electricity = new ElectricityAndTimeData();
        if (deviceList.containsValue(deviceList.get(bluetoothPosition))) {
            deviceList.get(bluetoothPosition).sendData(electricity.getElectricityData());
        } else {
//            Log.e("bluetoothPosition", bluetoothPosition);
        }
    }

    //从蓝牙连接类回调回来这个类
    public interface OnBleClickListenter {
        void onLink(BleDevice bleDevice);

        //获得连接状态
        void onState(int state);

        //非手动断开的情况
        void onExceptionDis(BleDevice device);

        //获得电量
        void getElectricity(byte[] data);

        //获取闹钟使能
        void getAlarmCan(byte[] data);

        //获取闹钟时间
        void getAlarmTime(byte[] data);
    }

    public void resigistBlueCallback(OnCallBackListener callBackListener) {
        this.callBackListener = callBackListener;
    }

    //从这个类回调出去
    public interface OnCallBackListener {
        void linkCall(String bluetoothPosition, BleDevice bleDevice);

        //连接状态
        void onState(int state, String bluetoothPosition, BleDevice bleDevice);

        //获得电量
        void getElectricity(byte[] data);

        //非手动断开的情况
        void onExceptionDis(String bluetoothPosition, BleDevice device);

        //获取闹钟使能
        void getAlarmCan(byte[] data);

        //获取闹钟时间
        void getAlarmTime(byte[] data);
    }

}